package com.google.gwt.sample.stockwatcher.client;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.moxieapps.gwt.highcharts.client.Chart;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DeckLayoutPanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ResizeLayoutPanel;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class StockWatcher implements EntryPoint, StockPricePublisher {

	private static final int REFRESH_INTERVAL = 1000; // ms
	private static final int ITEMS_EXAMINAR_INCREMENTO = 5;
	// private VerticalPanel mainPanel = new VerticalPanel();
	private FlexTable stocksFlexTable = new FlexTable();
	private HorizontalPanel addPanel = new HorizontalPanel();
	private TextBox newSymbolTextBox = new TextBox();
	private Button addStockButton = new Button("Add");
	private Label lastUpdatedLabel = new Label();
	private Label numAcciones = new Label();
	private Label accionMaxima = new Label();
	private Label accionMinima = new Label();
	private Label accionMedia = new Label();
	private ArrayList<String> stocks = new ArrayList<String>();
	private Button creditos = new Button("Creditos");
	private FlowPanel miChart = new FlowPanel();
	private VerticalPanel mainPanel = new VerticalPanel();
	static PopupPanel simplePopup;
	private HistoricoStockPrice hsp = new HistoricoStockPrice();
	private Double simularIncremento = 1.0; // para ej. 6
	private DeckLayoutPanel contentPanel;
	// Create a three-item tab panel, with the tab area 1.5em tall.
	private TabLayoutPanel p = new TabLayoutPanel(3, Unit.EM);
	private List<StockPriceObserver> stockPriceObservers = new ArrayList<StockPriceObserver>();

	/** * Entry point method. */
	public void onModuleLoad() {
		// TODO Create table for stock data.
		stocksFlexTable.setText(0, 0, "Symbol");
		stocksFlexTable.setText(0, 1, "Price");
		stocksFlexTable.setText(0, 2, "Change");
		stocksFlexTable.setText(0, 3, "Remove");
		stocksFlexTable.setText(0, 4, "Increment");
		stocksFlexTable.setText(0, 5, "Increment 5 intval"); // añadir esto para
																// el 6

		// Add styles to elements in the stock list table.
		stocksFlexTable.setCellPadding(6);
		stocksFlexTable.getRowFormatter().addStyleName(0, "watchListHeader");
		stocksFlexTable.addStyleName("watchList");
		stocksFlexTable.getCellFormatter().addStyleName(0, 1,
				"watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(0, 2,
				"watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(0, 3,
				"watchListRemoveColumn");

		// TODO Assemble Add Stock panel.
		StockPriceObserver stockPriceChart = new StockPriceChart();
		this.registerObserver(stockPriceChart);

		Widget chart = stockPriceChart.getWidget();
		miChart.add(chart);
		chart.setSize("90%", "auto");
		addPanel.add(newSymbolTextBox);
		addPanel.add(addStockButton);
		addPanel.add(creditos);
		addPanel.addStyleName("addPanel");
		// TODO Assemble Main panel.
		mainPanel.add(stocksFlexTable);
		mainPanel.add(addPanel);
		mainPanel.add(numAcciones);
		mainPanel.add(lastUpdatedLabel);
		mainPanel.add(accionMaxima);
		mainPanel.add(accionMinima);
		mainPanel.add(accionMedia);
		// TODO Associate the Main panel with the HTML host page.

		p.add(mainPanel, "tabla");
		p.add(miChart, "grafica");

		// Attach the LayoutPanel to the RootLayoutPanel. The latter will listen
		// for
		// resize events on the window to ensure that its children are informed
		// of
		// possible size changes.
		RootLayoutPanel rp = RootLayoutPanel.get();
		rp.add(p);

		// TODO Move cursor focus to the input box.
		newSymbolTextBox.setFocus(true);

		// Setup timer to refresh list automatically.
		Timer refreshTimer = new Timer() {
			@Override
			public void run() {
				refreshWatchList();
				for (StockPriceObserver observer : stockPriceObservers) {
					observer.onStockPricesUpdated(hsp, stocks);
				}
			}
		};
		refreshTimer.scheduleRepeating(REFRESH_INTERVAL);
		
		// Listen for mouse events on the Add button.
		addStockButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				addStock();

			}
		});

		creditos.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				showCredits();
			}

		});

		// Listen for keyboard events in the input box.
		newSymbolTextBox.addKeyDownHandler(new KeyDownHandler() {
			public void onKeyDown(KeyDownEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					addStock();
				}
			}
		});

	}

	/**
	 * Add stock to FlexTable. Executed when the user clicks the addStockButton
	 * or presses enter in the newSymbolTextBox.
	 */
	private void addStock() {
		final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
		newSymbolTextBox.setFocus(true);
		// Stock code must be between 1 and 10 chars that are numbers, letters,
		// or dots.
		if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")) {
			Window.alert("'" + symbol + "' is not a valid symbol.");
			newSymbolTextBox.selectAll();
			return;
		}

		newSymbolTextBox.setText("");

		// TODO Don't add the stock if it's already in the table.
		if (stocks.contains(symbol))
			return;
		// TODO Add the stock to the table.
		int row = stocksFlexTable.getRowCount();
		stocks.add(symbol);

		stocksFlexTable.setText(row, 0, symbol);
		stocksFlexTable.setWidget(row, 2, new Label());
		stocksFlexTable.setWidget(row, 1, new Label());
		stocksFlexTable.setWidget(row, 4, new Label()); // este es el widget del
														// incremento
		stocksFlexTable.setWidget(row, 5, new Label()); // añadimos label para
														// el ej. 6
		// TODO Add a button to remove this stock from the table.
		Button removeStockButton = new Button("x");
		removeStockButton.addStyleDependentName("remove");
		removeStockButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				int removedIndex = stocks.indexOf(symbol);
				stocks.remove(removedIndex);
				stocksFlexTable.removeRow(removedIndex + 1);
				hsp.removeStockPrice(symbol);
			}
		});
		stocksFlexTable.setWidget(row, 3, removeStockButton);
		stocksFlexTable.getCellFormatter().addStyleName(row, 1,
				"watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(row, 2,
				"watchListNumericColumn");
		stocksFlexTable.getCellFormatter().addStyleName(row, 3,
				"watchListRemoveColumn");
		// TODO Get the stock price.
		refreshWatchList();
		
		StockPrice stockPrice = hsp.getHistory(symbol).get(0);
		
		for (StockPriceObserver observer : stockPriceObservers) {
			observer.onStockPriceAdded(stockPrice);
		}
		
		

	}

	/**
	 * Generate random stock prices.
	 */
	private void refreshWatchList() {
		final double MAX_PRICE = 100.0; // $100.00
		final double MAX_PRICE_CHANGE = 0.02; // +/- 2%

		StockPrice[] prices = new StockPrice[stocks.size()];

		for (int i = 0; i < stocks.size(); i++) {
			double price = Random.nextDouble() * MAX_PRICE;
			double change = price * MAX_PRICE_CHANGE
					* (Random.nextDouble() * 2.0 - 1.0);

			if (stocks.get(i).equals("STUCOM")) {
				simularIncremento += 1.0;
				price = simularIncremento;
			}

			StockPrice sp = new StockPrice(stocks.get(i), price, change);

			prices[i] = sp;
			hsp.addStockPrice(sp); // para el ejercicio 5

			

		}

		// ejercicio 1
		numAcciones.setText("Hay " + stocks.size() + " acciones");
		updateTable(prices);
	}

	/**
	 * Update the Price and Change fields all the rows in the stock table.
	 * 
	 * @param prices
	 *            Stock data for all rows.
	 */
	private void updateTable(StockPrice[] prices) {
		for (int i = 0; i < prices.length; i++) {
			updateTable(prices[i]);
		}
		// aqui llamamos a la funcion del ejercicio 4 que calculara el valor max
		valorMaximo(prices);
	}

	/**
	 * Update a single row in the stock table.
	 * 
	 * @param price
	 *            Stock data for a single row.
	 */
	private void updateTable(StockPrice price) {
		// Make sure the stock is still in the stock table.
		if (!stocks.contains(price.getSymbol())) {
			return;
		}

		int row = stocks.indexOf(price.getSymbol()) + 1;

		// Format the data in the Price and Change fields.
		String priceText = NumberFormat.getFormat("#,##0.00").format(
				price.getPrice());
		NumberFormat changeFormat = NumberFormat
				.getFormat("+#,##0.00;-#,##0.00");
		String changeText = changeFormat.format(price.getChange());
		String changePercentText = changeFormat
				.format(price.getChangePercent());

		// Populate the Price and Change fields with new data.
		// stocksFlexTable.setText(row, 1, priceText);
		Label changeWidget = (Label) stocksFlexTable.getWidget(row, 2);
		changeWidget.setText(changeText + " (" + changePercentText + "%)");
		// Change the color of text in the Change field based on its value.
		String changeStyleName = "noChange";
		if (price.getChangePercent() < -0.1f) {
			changeStyleName = "negativeChange";
		} else if (price.getChangePercent() > 0.1f) {
			changeStyleName = "positiveChange";
		}
		changeWidget.setStyleName(changeStyleName);

		/* ejercicio 3 */
		Label priceWidget = (Label) stocksFlexTable.getWidget(row, 1);
		Label incrementWidget = (Label) stocksFlexTable.getWidget(row, 4);
		Label variosIncrementWidget = (Label) stocksFlexTable.getWidget(row, 5);
		priceWidget.setText(priceText + " €");
		changeStyleName = "noChange";
		if (price.getPrice() < 50) {
			changeStyleName = "negativeChange";
		} else if (price.getPrice() >= 50) {
			changeStyleName = "positiveChange";
		}

		priceWidget.setStyleName(changeStyleName);
		/* final ejercicio 3 */

		// Display timestamp showing last refresh.
		lastUpdatedLabel.setText("Last update : "
				+ DateTimeFormat.getFormat(
						DateTimeFormat.PredefinedFormat.DATE_TIME_MEDIUM)
						.format(new Date()));
		comprobarIncremento(price, incrementWidget);
		comprobarAccionesAlza(price, variosIncrementWidget); // llamamos funcion
																// ej. 6

	}

	/* ejercicio 2 */
	private void showCredits() {
		simplePopup = new PopupPanel(true);
		simplePopup.hide();
		simplePopup.setVisible(false);
		String msg = "<p>Author: Oscar Ca&ntilde;as</p><p> framework:GWT</p>"
				+ "<p>&copy; Copyright - 2014</p>";
		if (msg != null && !msg.equalsIgnoreCase("")) {
			simplePopup.ensureDebugId("cwBasicPopup-simplePopup");
			simplePopup.setWidget(new HTML(msg));
			simplePopup.setVisible(true);
			simplePopup.setPopupPosition(480, 250);
			simplePopup.setWidth("300px"); // 575
			simplePopup.setGlassEnabled(true);
			simplePopup.show();
		}
	}

	/* ejercicio 4 */
	private void valorMaximo(StockPrice[] prices) {

		List<StockPrice> lsp = Arrays.asList(prices);

		StockPrice maxSp = Collections.max(lsp);
		StockPrice minSp = Collections.min(lsp);

		Double total = 0.0;

		for (StockPrice sp : lsp) {
			total += sp.getPrice();
		}

		Double media = total / lsp.size();

		accionMaxima.setText("La accion con mas valor es: " + maxSp.getSymbol()
				+ " = " + formatearDecimales(maxSp.getPrice()));
		accionMinima.setText("La accion con menos valor es: "
				+ minSp.getSymbol() + " = "
				+ formatearDecimales(minSp.getPrice()));
		accionMedia.setText("El valor medio de las acciones es: "
				+ formatearDecimales(media));
	}

	/* ejercicio 5 */
	private void comprobarIncremento(StockPrice sp, Label incrementWidget) {
		List<StockPrice> lsp = hsp.getHistory(sp);
		incrementWidget.setText("");

		if (lsp != null && lsp.size() > 1) {
			StockPrice ultimo = lsp.get(lsp.size() - 1);
			StockPrice penultimo = lsp.get(lsp.size() - 2);

			Double priceUltimo = ultimo.getPrice();
			String strPriceUltimo = formatearDecimales(priceUltimo);
			Double pricePenultimo = penultimo.getPrice();
			String strPricePenultimo = formatearDecimales(pricePenultimo);
			Double incrementoPenultimo = pricePenultimo * 0.10;

			if (priceUltimo >= (pricePenultimo + incrementoPenultimo)) {
				incrementWidget.setText(strPricePenultimo + " "
						+ strPriceUltimo + " X");

			}
		}
	}

	private String formatearDecimales(Double cant) {
		String cantidad = NumberFormat.getFormat("#,##0.00").format(cant);
		return cantidad;
	}

	/* ejercicio 6 */
	private void comprobarAccionesAlza(StockPrice sp,
			Label variosIncrementWidtget) {
		List<StockPrice> lsp = hsp.getHistory(sp);
		List<String> precios = new ArrayList<String>();
		variosIncrementWidtget.setText("");
		if (lsp != null && lsp.size() >= 5) {
			boolean hayIncremento = true;

			List<StockPrice> sublsp = lsp.subList(lsp.size() - 5,
					lsp.size() - 1);

			for (int i = 0; i < (sublsp.size() - 1); i++) {

				StockPrice spAnterior = sublsp.get(i);
				StockPrice spSiguiente = sublsp.get(i + 1);

				if (spSiguiente.getPrice() <= spAnterior.getPrice()) {
					hayIncremento = false;
					break;
				}
			}

			/*
			 * for (int x = 1; x <= 5; x++) { StockPrice spActual =
			 * lsp.get(lsp.size() - x); StockPrice spAnterior =
			 * lsp.get(lsp.size() - (x + 1));
			 * 
			 * precios.add(spAnterior.getPrice() + " -> " + spActual.getPrice()
			 * + "\n ");
			 * 
			 * if (spActual.getPrice() <= spAnterior.getPrice()) { hayIncremento
			 * = false; break; } }
			 */

			if (hayIncremento) {
				variosIncrementWidtget.setText(" X");
			}

		}
	}

	/* ejercicio 7 */
	private void pintarGrafica(StockPrice sp) {

	}

	@Override
	public void registerObserver(StockPriceObserver stockPriceObserver) {
		stockPriceObservers.add(stockPriceObserver);

	}

	@Override
	public void notifyAllObservers() {
		// TODO Auto-generated method stub

	}

}
